using UnityEngine;
using System.Collections;

public class LoadScene : MonoBehaviour {
	
	public Transform barFrame;
	public Transform barSprite;
	public Transform barHead;
	public UILabel barLabel;
	
	AsyncOperation async;
	float progress;
	float maxScale;
	int frame;
	string barStr;

    ScenePlayerLogic scenePlayerLogic;

	// Use this for initialization
	void Start () 
    {
        if (Camera.mainCamera != null)
        {
            scenePlayerLogic = Camera.mainCamera.GetComponent<ScenePlayerLogic>();
        }

		StartCoroutine(Load());
		
		maxScale = barFrame.localScale.x - 160;
		
		frame = 0;
		barStr = barLabel.text;

        
	}
	
	IEnumerator Load(){
		//yield return new WaitForSeconds(4.0f);
        if (scenePlayerLogic != null) scenePlayerLogic.removeAllObjs();

		async = Application.LoadLevelAsync(SceneManagement.GetInstance().nextScene);
		
		yield return async;
	}
	
	// Update is called once per frame
	void Update () {
		if(SceneManagement.GetInstance().needBar == false) {
			barFrame.parent.gameObject.SetActive(false);
		} else {
			barFrame.parent.gameObject.SetActive(true);
		}
		
		progress =  async.progress;
		
		if(progress > 0.88f){
			progress = 1;
		}
		
		Vector3 scale = barSprite.localScale;
		scale.x = maxScale * progress;
		
		if(scale.x == 0f) scale.x = 0.001f;
		
		barSprite.localScale = scale;
		
		Vector3 position = barHead.localPosition;
		position.x = barSprite.localPosition.x + scale.x;
		barHead.localPosition = position;
		
		barLabel.text = barStr + (int)(progress * 100) + "%";
		
		Debug.Log(progress);
	}
}
